package camid.infrastructure;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

import camid.distribution.protocol.Endpoint;
import camid.distribution.protocol.MethodRequestMessage;
import camid.distribution.protocol.MethodResponseMessage;
import camid.distribution.protocol.ResponseStatus;
import camid.services.nodemanager.LookupInterceptor;


public class Connector 
{	
	private ObjectOutputStream outputMessage = null;
	private ObjectInputStream incomingMessage = null;
//	private Object responseMessage = null;
	
	private Socket conn = null;
	
	
	private Endpoint endpoint;
	
	private MethodResponseMessage response;
	
	public Connector(Endpoint ep){
//			conn = new Socket(host, port);
		this.endpoint = ep;
//		
	}
	
	public MethodResponseMessage sendReceive(MethodRequestMessage request)
	{
		MethodResponseMessage response = null;
		try 
		{
			String host = endpoint.getHostname();
			Integer port = endpoint.getPort();
			conn = new Socket(host, port);
			send(request);
			response = receive();
		} 
		catch (Exception e) 
		{
			e.printStackTrace();
			response = new MethodResponseMessage();
			response.setResponse(e);
			response.setStatus(ResponseStatus.RECEPTION_EXCEPTION);
			response.setEndpoint(endpoint);	
		}
		finally
		{
			end();
		}
		
		return response;
	}
	
	private void send(MethodRequestMessage request) throws IOException
	{ 	
		this.outputMessage = new ObjectOutputStream(conn.getOutputStream());
		this.outputMessage.writeObject(request);
		this.outputMessage.flush();
	}
	
	private MethodResponseMessage receive() throws ClassNotFoundException, IOException
	{
		MethodResponseMessage response = null;
//		try 
//		{
			this.incomingMessage = new ObjectInputStream(this.conn.getInputStream());
			response = (MethodResponseMessage) incomingMessage.readObject();
			response.setEndpoint(endpoint);
//		} 
//		catch (IOException e) 
//		{
//			e.printStackTrace();
//			
//		}
		return response;
	}
	
	public MethodResponseMessage getResponseMessage(){
		return this.response;
	}
	
	private void end()
	{
		if(incomingMessage != null)
		{
			try {
				incomingMessage.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if(outputMessage != null)
		{
			try {
				outputMessage.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		if(conn != null)
		{
			try {
				conn.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public Endpoint getEndpoint() {
		
		return this.endpoint;
	}
}